﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Riel_Gestion.entities;
using Riel_Gestion.dao;
using Riel_Gestion.printer;
using log4net;

namespace Riel_Gestion
{
    public partial class FrmVentasGenerales : Form
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(FrmVentasGenerales));
        Decimal saldoAnt = 0;
        int filasAct = 0;

        public FrmVentasGenerales()
        {
            InitializeComponent();
        }
               
     
        private void FrmVentasGenerales_Load(object sender, EventArgs e)
        {    
            vENTATableAdapter.FillByDate(rielDataSet.VENTA, DateTime.Now.Date);
            refreshSaldos();

            filasAct = vENTADataGridView.RowCount;
        }

        private void vENTABindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            logger.Info("Guardando ventas...");
            this.Validate();
            this.vENTABindingSource.EndEdit();
            int res = this.tableAdapterManager.UpdateAll(this.rielDataSet);

            if (res == 0)
            {
                logger.Info("No hay cambios para guardar");
                FrmMain.showInfoDialog("No hay cambios para guardar", "Guardar Venta");
            }

            if (res > 0)
            {
                logger.Info("Venta guardada exitosamente");
                FrmMain.showInfoDialog("Venta guardada exitosamente", "Guardar Venta");
            }

            if (res < 0)
            {
                logger.Info("Error al guardar venta");
                FrmMain.showInfoDialog("Error al guardar venta", "Guardar Venta");
            }
    
            refreshSaldos();
        }

        private void refreshSaldos()
        {
            logger.Info("Refrescando saldos...");
            DTOSaldo saldos = new DTOSaldo();
            saldos = VentaDAO.getSaldosTotalesByDates(DateTime.Now.Date, DateTime.Now.Date);

            lblTotDebe.Text = String.Format("{0:0.00}", saldos.TotDebe);
            lblTotHaber.Text = String.Format("{0:0.00}", saldos.TotHaber);
            lblTotSaldo.Text = String.Format("{0:0.00}", saldos.TotSaldo);

            lblTotSaldo.Font = new Font(lblTotSaldo.Font, FontStyle.Bold);

            lblTotSaldo.ForeColor = getForeColor(saldos.TotSaldo);
        }

        private Color getForeColor(Decimal value)
        {
            if (value > 0)
                return Color.Red;
            else if (value < 0)
                return Color.Green;
            else
                return Color.Blue;
        }

        private void vENTADataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {
                if (!vENTADataGridView.Rows[e.RowIndex].Cells[1].Value.ToString().Equals(""))
                {
                    if (ClienteDAO.exist(vENTADataGridView.Rows[e.RowIndex].Cells[1].Value.ToString())!= 0)
                    {
                        DTOSaldo saldos = VentaDAO.getSaldosTotalesById(vENTADataGridView.Rows[e.RowIndex].Cells[1].Value.ToString());
                        vENTADataGridView.Rows[e.RowIndex].Cells[5].Value = saldos.TotSaldo;
                        saldoAnt = saldos.TotSaldo;
                    }
                    else
                    {
                        FrmMain.showErrorDialog("El cliente ingresado no existe.");                        
                    }
                }
            }

            if (e.ColumnIndex == 3)
            {
                if ("".Equals(vENTADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()))
                    vENTADataGridView.Rows[e.RowIndex].Cells[3].Value = 0;

                if ("".Equals(vENTADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString()))
                    vENTADataGridView.Rows[e.RowIndex].Cells[4].Value = 0;

                vENTADataGridView.Rows[e.RowIndex].Cells[5].Value = saldoAnt + Decimal.Parse(vENTADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()) - Decimal.Parse(vENTADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString());
            }


            if (e.ColumnIndex == 4)
            {
                if ("".Equals(vENTADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()))
                    vENTADataGridView.Rows[e.RowIndex].Cells[3].Value = 0;

                if ("".Equals(vENTADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString()))
                    vENTADataGridView.Rows[e.RowIndex].Cells[4].Value = 0;

                vENTADataGridView.Rows[e.RowIndex].Cells[5].Value = saldoAnt + Decimal.Parse(vENTADataGridView.Rows[e.RowIndex].Cells[3].Value.ToString()) - Decimal.Parse(vENTADataGridView.Rows[e.RowIndex].Cells[4].Value.ToString());
            }

        }
       
        private void vENTADataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex == vENTADataGridView.Rows.Count - 1)
                vENTADataGridView.Rows[e.RowIndex].Cells[0].Value = DateTime.Now.Date;
        }

        private void vENTADataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            //vENTADataGridView.CurrentCell = vENTADataGridView[e.ColumnIndex, e.RowIndex];
            //vENTADataGridView.BeginEdit(true);           
        }

        private void btnAceptar_Click(object sender, EventArgs e)
        {
            if (filasAct != vENTADataGridView.RowCount)
                if (FrmMain.showInfoYesNoDialog("¿Desea guardar los cambios?", "Ventas") == DialogResult.Yes)
                    vENTABindingNavigatorSaveItem_Click(sender, e);
            
            this.Close();
        }

        //------------- Opcional ------------------
        /*
        private AutoCompleteStringCollection autoCompleteCodCliente()
        {
            AutoCompleteStringCollection cods = new AutoCompleteStringCollection();
            rielDataSetTableAdapters.CLIENTETableAdapter cli = new Riel_Gestion.rielDataSetTableAdapters.CLIENTETableAdapter();
            Riel_Gestion.rielDataSet.CLIENTEDataTable table = cli.GetDataCodCliente();

            foreach (DataRow fila in table)
            {
                cods.Add(fila["CODCLIENTE"].ToString());
            }

            return cods;
        }

        private void vENTADataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (vENTADataGridView.Columns[vENTADataGridView.CurrentCell.ColumnIndex].HeaderText.Equals("CLIENTE"))
            {
                TextBox tb = (TextBox) e.Control;

                if (tb != null)
                {
                    tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                    tb.AutoCompleteCustomSource = autoCompleteCodCliente();
                    tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
                }
            }
        }
        */
        private void btnImprimir_Click(object sender, EventArgs e)
        {
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
            PrinterImpl printer = new PrinterImpl(vENTADataGridView, "Ventas del " + String.Format("{0:dd/MM/yyyy}", DateTime.Now));
                                    
            printPreviewDialog.Document = printer.getDocument();
            if (printPreviewDialog.ShowDialog() == DialogResult.OK)
            {
                logger.Info("Imprimiendo...");
                printer.print();
            }
        }


    }
}
